package com.nmgydy.util;

import java.io.IOException;

import net.spy.memcached.AddrUtil;
import net.spy.memcached.BinaryConnectionFactory;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.internal.OperationFuture;

public class MemcachedUtil {
	
	private static final String connectUrl = ConfigUtil.getValue("memcached.url");
	
	/** 获取连接 */
	public static MemcachedClient openClient(){
		try {
			MemcachedClient client = new MemcachedClient(new BinaryConnectionFactory(), AddrUtil.getAddresses(connectUrl));
			return client;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/** 设置值 */
	public static boolean set(String key,Object value,int expireTime){
		MemcachedClient client = openClient();
		try {
			OperationFuture<Boolean> future = client.set(key, expireTime, value);
			return future.get();
		}catch (Exception e) {
			e.printStackTrace();
			return false;
		}finally{
			if(client != null){
				client.shutdown();
			}
		}
	}
	/** 设置值-永不过期 */
	public static boolean set(String key,Object value){
		MemcachedClient client = openClient();
		try {
			OperationFuture<Boolean> future = client.set(key, 0, value);
			return future.get();
		}catch (Exception e) {
			e.printStackTrace();
			return false;
		}finally{
			if(client != null){
				client.shutdown();
			}
		}
	}
	
	/** 获取值 */
	public static Object get(String key){
		MemcachedClient client = openClient();
		try {
			return client.get(key);
		}catch (Exception e) {
			e.printStackTrace();
			return null;
		}finally{
			if(client != null){
				client.shutdown();
			}
		}
	}
	
	public static void main(String[] args) {
		boolean res = set("aaa", "bbb",30);
		System.out.println(res);
		System.out.println(get("aaa"));
	}
	
}
